<?php

use think\Cache;

function created_data($table_name = ''){
    //`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    $sql = " CREATE TABLE IF NOT EXISTS `$table_name` (
`material_code` VARCHAR (32) DEFAULT '' COMMENT '编号',
`material_name` VARCHAR (32) DEFAULT '' COMMENT '名称',
`material_model` VARCHAR (48) DEFAULT '' COMMENT '型号',
`material_unit` VARCHAR (12) DEFAULT '' COMMENT '单位',
`material_price` decimal (10,2) DEFAULT '0.00' COMMENT '单价',
`material_num` VARCHAR (32) DEFAULT '0' COMMENT '数量',
`update_time` VARCHAR (32) DEFAULT '' COMMENT '更新时间',
  PRIMARY KEY (`material_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='库存表';";
    return $sql;
}

/**
 * 获取四位随机验证码
 * @author wyf
 * Time: 2019-05-28
 */
function getRandCode()
{
    return mt_rand(1000, 9999);
}


/**
 * 接口返回json数据
 * @param $code
 * @param string $msg
 * @param array $data
 * @return array
 * @author wyf
 * Time: 2019-05-29
 */
function return_json($msg = '', $code = 200, $data = array())
{
    if (empty($data)) {
        $return = array('msg' => (string)$msg, 'code' => (int)$code);
    } else {
        $return = array('msg' => (string)$msg, 'code' => (int)$code, 'data' => $data);
    }
    header('Content-Type:application/json; charset=utf-8');
    echo json_encode($return);
}

/**
 * 生成访问令牌
 * @param $id
 * @return string
 * @author wyf
 * Time: 2019-05-29
 */
function creatToken($id)
{
    return strtolower(md5($id . time()) . str_rand(8));
}

/*
 * 生成随机字符串
 * @param int $length 生成随机字符串的长度
 * @param string $char 组成随机字符串的字符串
 * @return string $string 生成的随机字符串
 */
function str_rand($length = 32, $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
    if (!is_int($length) || $length < 0) {
        return false;
    }
    $string = '';
    for ($i = $length; $i > 0; $i--) {
        $string .= $char[mt_rand(0, strlen($char) - 1)];
    }
    return $string;
}

/**
 * 获取真实ip
 * @return array|false|string
 * @author wyf
 * Time: 2019-05-29
 */
function get_client_ip()
{

    $ip = '';
    $ip = request()->ip();
    return $ip;
    //下面的代码报错  不知道为啥不能用
//    if (getenv("HTTP_CLIENT_IP")){
//        $ip = getenv("HTTP_CLIENT_IP");
//    }elseif(getenv("HTTP_X_FORWARDED_FOR")){
//        $ip = getenv("HTTP_X_FORWARDED_FOR");
//    }elseif(getenv("REMOTE_ADDR")){
//        $ip = getenv("REMOTE_ADDR");
//    }
//    return $ip;
}

/**
 * 验证手机号是否正确
 * @param $mobile
 * @return bool
 * @author wyf
 * Time: 2019-05-29
 */
function isMobileNum($mobile)
{
    return preg_match('/^((\(\d{3}\))|(\d{3}\-))?13[0-9]\d{8}$|14[0-9]\d{8}$|15[0-9]\d{8}$|16[0-9]\d{8}$|17[0-9]\d{8}$|18[0-9]\d{8}$|19[0-9]\d{8}$/', $mobile) ? true : false;
}

/**
 * 检测返回的字段是否有null 如果有处理成空字符串
 * @author wyf
 * Time: 2019-06-04
 */
function checkNullToString($data)
{
    foreach ($data as $key => $value) {
        if (is_null($value) === true) {
            $data[$key] = "";
        }
    }
    return $data;
}

/**
 * curl小程序消息模板请求
 * @param string $url 请求目标url
 * @param string $data 要发送的POST数据
 * @param string $type 数据类型
 * @author wyf
 * @date 2019-05-27
 */
function Http($url, $data, $type = "http")
{
    $curl = curl_init();

    if ($type == "json") {
        $headers = array(
            "Content-type: application/json;charset=UTF-8",
            "Accept: application/json;charset=utf-8"
        );
        $data = json_encode($data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}


/**
 * 二维数组根据字段进行排序
 * @params array $array 需要排序的数组
 * @params string $field 排序的字段
 * @params string $sort 排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
 */
function arraySequence($array, $field, $sort = 'SORT_ASC')
{
    $arrSort = array();
    foreach ($array as $uniqid => $row) {
        foreach ($row as $key => $value) {
            $arrSort[$key][$uniqid] = $value;
        }
    }
    array_multisort($arrSort[$field], constant($sort), $array);
    return $array;

}

/**
 * 合并数组
 * @param array $arr1
 * @param array $arr2
 * @return array
 * @author ph
 * Time: 2019-06-15
 */
function mergeArrayFun($arr1, $arr2)
{
    $arr = [];
    if ($arr1 && $arr2) {
        $arr = array_merge($arr1, $arr2);
    } elseif (empty($arr1) && $arr2) {
        $arr = $arr2;
    } elseif ($arr1 && empty($arr2)) {
        $arr = $arr1;
    }
    return $arr;
}

/**
 * unicode解码方法
 * @params string $unicode_str unicode字符串
 * wyf
 * time:2019-06-15
 */
function unicodeDecode($unicode_str)
{
    $json = '{"str":"' . $unicode_str . '"}';
    $arr = json_decode($json, true);
    if (empty($arr)) return '';
    return $arr['str'];
}


//同比/环比增长的函数
//$a 是今日数据
//$b 是上个期限的数据
function compareAdd($a, $b)
{
    $a = (int)$a;
    $b = (int)$b;
    if ($a == 0 || $b == 0) {
        $he = round(($a - $b), 2) * 100;
    } else {
        $he = round(($a - $b) / $b, 2) * 100;
    }
    return $he . '%';

}


/**
 * 手机号码替换*号
 * @param $mobile
 * @return mixed
 * @author wyf
 * Time: 2019-06-21
 */
function mobileReplaceAsterisk($mobile)
{
    return substr_replace($mobile, '****', 3, 4);
}

/**
 * php获取毫秒级的时间戳
 * @return float
 * @author wyf
 * Time: 2019-07-08
 */
function msectime()
{
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}


/**
 * 判断是否为合法的身份证号码
 * @param $mobile
 * @return int
 */
function isCreditNo($vStr)
{
    $vCity = array(
        '11', '12', '13', '14', '15', '21', '22',
        '23', '31', '32', '33', '34', '35', '36',
        '37', '41', '42', '43', '44', '45', '46',
        '50', '51', '52', '53', '54', '61', '62',
        '63', '64', '65', '71', '81', '82', '91'
    );
    if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
    if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
    $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
    $vLength = strlen($vStr);
    if ($vLength == 18) {
        $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
    } else {
        $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
    }
    if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
    if ($vLength == 18) {
        $vSum = 0;
        for ($i = 17; $i >= 0; $i--) {
            $vSubStr = substr($vStr, 17 - $i, 1);
            $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
        }
        if ($vSum % 11 != 1) return false;
    }
    return true;
}

/**
 * 根据KEY值分组
 */
function array_group_by($arr, $key)
{
    $grouped = [];
    foreach ($arr as $value) {
        $grouped[$value[$key]][] = $value;
    }
    if (func_num_args() > 2) {
        $args = func_get_args();
        foreach ($grouped as $key => $value) {
            $parms = array_merge([$value], array_slice($args, 2, func_num_args()));
            $grouped[$key] = call_user_func_array('array_group_by', $parms);
        }
    }
    return $grouped;
}

/**
 *  分时秒转秒数
 * @param string $str
 * @return float|int
 */
function strtosecond($str)
{
    $arr = explode(':', $str);
    return $arr[0] * 3600 + $arr[1] * 60 + $arr[2];
}

/**
 *  秒数转分时秒字符串
 * @param int秒数
 * @return str
 */
function secondtostr($second)
{
    $str = '';
    //取整补0
    $str .= sprintf("%02d", floor($second / 3600));
    //补上冒号
    $str .= ':';
    $str .= sprintf("%02d", floor(($second % 3600) / 60));
    $str .= ':';
    $str .= sprintf("%02d", $second % 60);
    return $str;
}

//php请求网络的方法
function curl_get($url, &$httpCode = 0)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //不做证书校验,部署在linux环境下请改为true
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $file_contents = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $file_contents;
}


/**
 * 根据起点坐标和终点坐标测距离
 * @param  [array]   $from     [起点坐标(经纬度),例如:array(118.012951,36.810024)]
 * @param  [array]   $to     [终点坐标(经纬度)]
 * @param  [bool]    $km        是否以公里为单位 false:米 true:公里(千米)
 * @param  [int]     $decimal   精度 保留小数位数
 * @return [string]  距离数值
 */
function get_distance($from, $to, $km = true, $decimal = 2)
{
    $from = explode(',', $from);
    $to = explode(',', $to);
    $EARTH_RADIUS = 6370.996; // 地球半径系数
    $distance = $EARTH_RADIUS * 2 * asin(sqrt(pow(sin(($from[0] * pi() / 180 - $to[0] * pi() / 180) / 2), 2) + cos($from[0] * pi() / 180) * cos($to[0] * pi() / 180) * pow(sin(($from[1] * pi() / 180 - $to[1] * pi() / 180) / 2), 2))) * 1000;
    if ($km) {
        $distance = $distance / 1000;
    }
    return round($distance, $decimal);

}
